<?php
namespace control;
/*
*采购汇总表类
*/

class purchaseStatisticsClass extends adIndexClass
{
    private const page = 'purchaseStatistics';
    private const title = '采购汇总表';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            case 'supplierSearch':
                $tr = [
                    'supplierCode'          => [
                        'name'  => '供应商编码',
                        'width' => 150,
                    ],
                    'supplierName'          => [
                        'name'  => '供应商',
                        'width' => 150,
                    ],
                    'code'          => [
                        'name'  => '物料编码',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'materialName' => [
                        'name'  => "物料名称",
                        'width' => 150,
                    ],
                    'model'  => [
                        'name'  => "规格型号",
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'unit'         => [
                        'name'  => '单位',
                        'width' => 100,
                    ],
                    'num'          => [
                        'name'  => '采购数量',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'price'          => [
                        'name'  => '单价('.static::$unit.')',
                        'width' => 150,
                    ],
                    'notaxMoney'          => [
                        'name'  => '未税金额('.static::$unit.')',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'taxMoney'          => [
                        'name'  => '税额('.static::$unit.')',
                        'width' => 130,
                        'sort' => 1,
                    ],
                    'money'          => [
                        'name'  => '价税合计('.static::$unit.')',
                        'width' => 130,
                        'sort' => 1,
                    ]
                ];
                break;
            default:
                $tr = [
                    'code'          => [
                        'name'  => '物料编码',
                        'width' => 250,
                        'sort' => 1,
                    ],
                    'materialName' => [
                        'name'  => "物料名称",
                        'width' => 250,
                    ],
                    'model'  => [
                        'name'  => "规格型号",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'unit'         => [
                        'name'  => '单位',
                        'width' => 100,
                    ],
                    'num'          => [
                        'name'  => '采购数量',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'price'          => [
                        'name'  => '单价('.static::$unit.')',
                        'width' => 150,
                    ],
                    'notaxMoney'          => [
                        'name'  => '未税金额('.static::$unit.')',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'taxMoney'          => [
                        'name'  => '税额('.static::$unit.')',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'money'          => [
                        'name'  => '价税合计('.static::$unit.')',
                        'width' => 150,
                        'sort' => 1,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "物料编码" => text(array("name" => "code")),
                    "物料名称"   => text(array("name" => "materialName")),
                    '单据日期' => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."',source:'material',classify:'采购商品汇总'})\">导出</span>";
        }
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "c.name" => $this->post('materialName'),
            "c.code" => $this->post('code'),
        );
        //全等查询数组
        $equal = array(
            "a.coid"=>self::$coid,
            "b.state"=>'已确认'
        );
        $and = "";
        if ($this->post('createTime')) {
            //单据日期
            $timeArr = explode(' ~ ', $this->post('createTime'));
            $and .= " and b.recordDate >='{$timeArr[0]}' and b.recordDate <='{$timeArr[1]}'";
        }
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and." group by a.materialId,a.unit";
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'code',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        $page = $this->page(array(
            "table" => "purchase_order_detail as a join purchase_order as b on a.orderId = b.id join material as c on c.id = a.materialId",
            'field'=>"
            any_value(c.code) as code,
            any_value(c.name) as materialName,
            any_value(c.model) as model,
            a.unit,
            any_value(a.materialId) as materialId,
            ifnull(sum(any_value(a.num)),0) as num,
            ifnull(sum(any_value(a.money)),0) as money,
            ifnull(sum(any_value(a.taxMoney)),0) as taxMoney,
            ifnull(sum(any_value(a.money)-any_value(a.taxMoney)),0) as notaxMoney
            ",
            "where" => $where,
            "order" => $orderBy['orderBy']));
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array();
        //获取记录
        foreach ($page['array'] as $array) {
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "num":
                        $row[] = self::lostZero($array['num'],'numPrecision');
                        break;
                    case "price":
                        $price = $array['num']>0? self::formattingFigure($array['money']/$array['num'],'pricePrecision'):0;
                        $row[] = $price;
                        break;
                    case "notaxMoney":
                    case "taxMoney":
                    case "money":
                        $row[] = self::lostZero($array[$key]);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => "purchase_order_detail as a join purchase_order as b on a.orderId = b.id join material as c on c.id = a.materialId",
            'single' => search(array("like" => $like, "=" => $equal)) . $and,
            'field'  => "ifnull(sum(a.num),0) as num,
            ifnull(sum(a.money),0) as money,
            ifnull(sum(a.taxMoney),0) as taxMoney,
            ifnull(sum(a.money-a.taxMoney),0) as notaxMoney",
        ]);
        $total    = [
            'num'        => self::lostZero($totalQuery['num'], 'numPrecision'),
            'notaxMoney'   => self::lostZero($totalQuery['notaxMoney']),
            'taxMoney' => self::lostZero($totalQuery['taxMoney']),
            'money' => self::lostZero($totalQuery['money']),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function supplierOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "供应商编码" => text(array("name" => "supplierCode")),
                    "供应商"   => supplierClass::supplierSelect(array('title' => '')),
                    "物料编码" => text(array("name" => "code")),
                ],
                [
                    "物料名称"   => text(array("name" => "materialName")),
                    '单据日期' => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /**
     * 按供应商
     * @return bool|string
     */
    public function supplier(){
        $html = $this->supplierOptions(false);
        //控件
        $button = "";
        if ($this->power('supplierPurchaseStatistics', "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."',source:'supplier',classify:'采购供应商汇总'})\">导出</span>";
        }
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /**
     * 按供应商
     * @return bool|string
     */
    public function supplierSearch()
    {
        //like查询数组
        $like = array(
            "c.name" => $this->post('materialName'),
            "c.code" => $this->post('code'),
        );
        //全等查询数组
        $equal = array(
            "a.coid"=>self::$coid,
            "b.state"=>'已确认',
            "b.supplierId"=>$this->post('supplierId')
        );
        $and = "";
        if ($this->post('clientCode')) {
            $and.=" and b.supplierId in (select id from supplier where code like '%".$this->post('supplierCode')."%' and coid = '".self::$coid."')";
        }
        if ($this->post('createTime')) {
            //单据日期
            $timeArr = explode(' ~ ', $this->post('createTime'));
            $and .= " and b.recordDate >='{$timeArr[0]}' and b.recordDate <='{$timeArr[1]}'";
        }
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and." group by b.supplierId,a.materialId,a.unit";
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'code',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        $page = $this->page(array(
            "table" => "purchase_order_detail as a join purchase_order as b on a.orderId = b.id join material as c on c.id = a.materialId",
            'field'=>"
            b.supplierId,
            any_value(c.code) as code,
            any_value(c.name) as materialName,
            any_value(c.model) as model,
            a.unit,
            any_value(a.materialId) as materialId,
            ifnull(sum(any_value(a.num)),0) as num,
            ifnull(sum(any_value(a.money)),0) as money,
            ifnull(sum(any_value(a.taxMoney)),0) as taxMoney,
            ifnull(sum(any_value(a.money)-any_value(a.taxMoney)),0) as notaxMoney
            ",
            "where" => $where,
            "order" => $orderBy['orderBy']
        ));
        $_SESSION[self::page]['supplier'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array();
        //获取记录
        foreach ($page['array'] as $array) {
            $supplier = query('supplier',"id = '$array[supplierId]'");
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "supplierCode":
                        $row[] = $supplier['code'];
                        break;
                    case "supplierName":
                        $row[] = $supplier['name'];
                        break;
                    case "num":
                        $row[] = self::lostZero($array['num'],'numPrecision');
                        break;
                    case "price":
                        $price =$array['num']>0? self::formattingFigure($array['money']/$array['num'],'pricePrecision'):0;
                        $row[] = $price;
                        break;
                    case "notaxMoney":
                    case "taxMoney":
                    case "money":
                        $row[] = self::lostZero($array[$key]);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => "purchase_order_detail as a join purchase_order as b on a.orderId = b.id join material as c on c.id = a.materialId",
            'single' => search(array("like" => $like, "=" => $equal)) . $and,
            'field'  => "ifnull(sum(a.num),0) as num,
            ifnull(sum(a.money),0) as money,
            ifnull(sum(a.taxMoney),0) as taxMoney,
            ifnull(sum(a.money-a.taxMoney),0) as notaxMoney",
        ]);
        $total    = [
            'num'        => self::lostZero($totalQuery['num'], 'numPrecision'),
            'notaxMoney'   => self::lostZero($totalQuery['notaxMoney']),
            'taxMoney' => self::lostZero($totalQuery['taxMoney']),
            'money' => self::lostZero($totalQuery['money']),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 导出
     */
    public function exportData()
    {
        $source = $this->get('source');
        $power = $source == 'supplier' ? 'supplierPurchaseStatistics' : self::page;
        $templateId = $this->get('templateId');
//        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power($power, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        }  elseif(empty($source)){
            $_SESSION['warn'] = '未找到类型';
        }else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            if($source =='supplier'){
                $sql = $_SESSION[self::page]['supplier'];
                $result = sqlFind($sql);
                //导出数据生成
                foreach ($result as $array){
                    $column = [];
                    $price =$array['num']>0? self::formattingFigure($array['money']/$array['num'],'pricePrecision'):0;
                    $supplier = query('supplier',"id = '$array[supplierId]'");
                    foreach ($tempFieldAll as $templateField){
                        if ($templateField['display']){
                            $column[] = match ($templateField['columnName']){
                                '供应商编码'=>$supplier['code'],
                                '供应商'=>$supplier['name'],
                                '物料编码'=>$array['code'],
                                '物料名称'=>$array['materialName'],
                                '规格型号'=>$array['model'],
                                '单位'=>$array['unit'],
                                '采购数量'=>self::lostZero($array['num'],'numPrecision'),
                                '单价'=>$price,
                                '未税金额'=>self::lostZero($array['notaxMoney']),
                                '税额'=>self::lostZero($array['taxMoney']),
                                '价税合计'=>self::lostZero($array['money']),
                                default=>'',
                            };
                        }
                    }
                    $data[] = $column;
                }
            }else{
                $sql = $_SESSION[self::page]['sql'];
                $result = sqlFind($sql);
                //导出数据生成
                foreach ($result as $array){
                    $column = [];
                    $price =$array['num']>0? self::formattingFigure($array['money']/$array['num'],'pricePrecision'):0;
                    foreach ($all['array'] as $templateField){
                        if ($templateField['display']){
                            $column[] = match ($templateField['columnName']){
                                '物料编码'=>$array['code'],
                                '物料名称'=>$array['materialName'],
                                '规格型号'=>$array['model'],
                                '单位'=>$array['unit'],
                                '采购数量'=>self::lostZero($array['num'],'numPrecision'),
                                '单价'=>$price,
                                '未税金额'=>self::lostZero($array['notaxMoney']),
                                '税额'=>self::lostZero($array['taxMoney']),
                                '价税合计'=>self::lostZero($array['money']),
                                default=>'',
                            };
                        }
                    }
                    $data[] = $column;
                }
            }

            $text = $this->control['name'] . "导出了采购汇总表";
            $this->logText(["type" => $power, "text" => $text]);
            $this->excelOut($title, $data, "采购汇总表.xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            '采购供应商汇总'=>[
                [
                    'columnName'=>'供应商编码',
                    'aliasName'=>'供应商编码',
                ],
                [
                    'columnName'=>'供应商',
                    'aliasName'=>'供应商',
                ],
                [
                    'columnName'=>'物料编码',
                    'aliasName'=>'物料编码',
                ],
                [
                    'columnName'=>'物料名称',
                    'aliasName'=>'物料名称',
                ],
                [
                    'columnName'=>'规格型号',
                    'aliasName'=>'规格型号',
                ],
                [
                    'columnName'=>'单位',
                    'aliasName'=>'单位',
                ],
                [
                    'columnName'=>'采购数量',
                    'aliasName'=>'采购数量',
                ],
                [
                    'columnName'=>'单价',
                    'aliasName'=>'单价(元)',
                ],
                [
                    'columnName'=>'未税金额',
                    'aliasName'=>'未税金额(元)',
                ],
                [
                    'columnName'=>'税额',
                    'aliasName'=>'税额(元)',
                ],
                [
                    'columnName'=>'价税合计',
                    'aliasName'=>'价税合计(元)',
                ],
            ],
            default=>  [
                [
                    'columnName'=>'物料编码',
                    'aliasName'=>'物料编码',
                ],
                [
                    'columnName'=>'物料名称',
                    'aliasName'=>'物料名称',
                ],
                [
                    'columnName'=>'规格型号',
                    'aliasName'=>'规格型号',
                ],
                [
                    'columnName'=>'单位',
                    'aliasName'=>'单位',
                ],
                [
                    'columnName'=>'采购数量',
                    'aliasName'=>'采购数量',
                ],
                [
                    'columnName'=>'单价',
                    'aliasName'=>'单价(元)',
                ],
                [
                    'columnName'=>'未税金额',
                    'aliasName'=>'未税金额(元)',
                ],
                [
                    'columnName'=>'税额',
                    'aliasName'=>'税额(元)',
                ],
                [
                    'columnName'=>'价税合计',
                    'aliasName'=>'价税合计(元)',
                ],
            ]
        };
    }
}

